package com.zhku.book.controller;


import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sun.tools.corba.se.idl.ExceptionEntry;
import com.zhku.book.pojo.Book;
import com.zhku.book.pojo.BookCategory;
import com.zhku.book.pojo.resp.BookResp;
import com.zhku.book.pojo.resp.PageResp;
import com.zhku.book.service.BookCategoryService;
import com.zhku.book.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * @ClassName : BookController  //类名
 * @Description : 图书控制类  //描述
 * @Author : ZoZou02 //作者
 * @Date: 2024/3/13  11:08
 */
@RestController
public class BookController {

    @Autowired
    private BookService bookService;

    @Autowired
    private BookCategoryService bookCategoryService;

    @GetMapping("/getBookList")
    public PageResp<BookResp> getBookList(Integer page, Integer size, Integer id){
        PageResp<BookResp> resp = new PageResp<BookResp>();
        Page<BookResp> bookPage = new Page<>(page,size);
        bookPage = (Page<BookResp>) bookService.findBookAndCategory(bookPage, id);
        resp.setList(bookPage.getRecords());
        resp.setTotal(bookPage.getTotal());
        return resp;
    }

    @GetMapping("/getBookListCategory")
    public List<BookCategory> getBookCategoryList(){
        List<BookCategory> list = bookCategoryService.list();
        return list;
    }

    @PostMapping("/saveOrUpdate")
    public String saveOrUpdate(@RequestBody Book book) {
        try {
            if (Objects.isNull(book.getSelfTime())) {
                book.setSelfTime(new Date());
            }
            bookService.saveOrUpdate(book);
            return "操作成功";
        } catch (Exception e) {
            e.printStackTrace();
            return "操作失败";
        }
    }

    @GetMapping("/deleteBook/{id}")
    public String deleteBook(@PathVariable("id") Integer id) {
        try {
            bookService.removeById(id);
            return "删除成功";
        } catch (Exception e) {
            e.printStackTrace();
            return "删除失败";
        }
    }

}
